package com.yudi.blog.bussiness.service.impl;

import com.yudi.blog.bussiness.dao.BlogRepository;
import com.yudi.blog.bussiness.dto.Blog;
import com.yudi.blog.bussiness.service.BlogService;
import com.yudi.blog.bussiness.service.TagService;
import com.yudi.blog.bussiness.vo.BlogQueryVO;
import com.yudi.blog.exception.NotFoundException;
import com.yudi.blog.utils.MarkDownUtils;
import com.yudi.blog.utils.MyBeanUtils;
import com.yudi.blog.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.util.*;

/**
 * @Author YuDi
 * @Date 2021/11/11 11:47
 * @Version 1.0
 */
@Service
public class BlogServiceImpl implements BlogService {

    @Autowired
    private BlogRepository blogRepository;

    @Autowired
    private TagService tagService;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Blog getBlog(Long id) {
        return blogRepository.getById(id);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Blog getAndConvert(Long id) {

        blogRepository.updateView(id);
        Blog blog = blogRepository.getById(id);

        if(blog == null){
            throw new NotFoundException("不存在该博客");
        }
        Blog b = new Blog();
        BeanUtils.copyProperties(blog, b);
        String c = MarkDownUtils.markdownToHtmlExtensions(b.getContent());
        b.setContent(c);

        return b;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Page listBlog(Pageable pageable, BlogQueryVO blog) {

        return blogRepository.findAll(new Specification<Blog>() {
            @Override
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();
                if(!StringUtils.isEmpty(blog.getTitle())){
                    list.add(cb.like(root.<String>get("title"), "%" + blog.getTitle() + "%"));
                }

                if(blog.getRecommend() != null){
                    list.add(cb.equal(root.<Boolean>get("recommend"), blog.getRecommend()));
                }

                if(blog.getTypeId() != null){
                    list.add(cb.equal(root.<Long>get("type"), blog.getTypeId()));
                }
                cq.where(list.toArray(new Predicate[list.size()]));
                return null;
            }
        }, pageable);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Page listBlog(Pageable pageable, Long tagId) {

        return blogRepository.findAll(new Specification<Blog>() {
            @Override
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                Join join = root.join("tags");
                return cb.equal(join.get("id"), tagId);
            }
        }, pageable);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Page listBlog(Pageable pageable) {
        return blogRepository.findAll(pageable);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Page<Blog> listBlog(String query, Pageable pageable) {
        return blogRepository.findByQuery(query, pageable);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<Blog> listRecommendBlogTop(Integer size) {

        Sort sort = Sort.by(Sort.Direction.DESC, "updateTime");
        Pageable pageable = PageRequest.of(0, size, sort);

        return blogRepository.findTop(pageable);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map<String, List<Blog>> archiveBlog() {

        Map<String, List<Blog>> map = new HashMap<>();
        List<String> years =  blogRepository.findGroupYear();

        for(String year : years){
            List<Blog> t = blogRepository.findByYear(year);
            map.put(year, t);
        }

        return map;
    }

    @Override
    public Long countBlog() {
        return blogRepository.count();
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Blog save(Blog blog) {
        blog.setCreateTime(new Date());
        blog.setUpdateTime(new Date());
        blog.setViews(0);
        return blogRepository.save(blog);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Blog update(Long id, Blog blog) {
        blog.setUpdateTime(new Date());

        if(blog.getViews() == null){
            blog.setViews(0);
        }
        blog.setViews(blog.getViews() + 1);
        blog.setTags(tagService.listTag(blog.getTagIds()));

        Blog t = blogRepository.getById(id);
        if(t == null){
            throw new NotFoundException("没有该博客");
        }

        BeanUtils.copyProperties(blog, t, MyBeanUtils.getNullPropertyNames(blog));
        return blogRepository.save(t);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(Long id) {
        blogRepository.deleteById(id);
    }
}
